/* global window */
/* global document */
/* global location */
import { routerRedux } from 'dva/router'
import { parse } from 'qs'
import { request, config } from 'utils';
import { query,logout,changePassWordService} from 'services/app'
import * as menuService from 'services/menu'
import { refreshTokenByOrg } from 'services/auth'
const { prefix } = config

export default {
  namespace: 'app',
  
  state: {
    user: {},
    permissions: {
      visit: [],
    },
    menu: [
      {
        id: 1,
        icon: 'laptop',
        name: 'Dashboard',
        router: '/dashboard',
      },
    ],
    orgList: [],
    currentOrg: null,
    menuPopoverVisible: false,
    siderFold: window.localStorage.getItem(`${prefix}siderFold`) === 'true',
    darkTheme: window.localStorage.getItem(`${prefix}darkTheme`) === 'true',
    isNavbar: document.body.clientWidth < 769,
    navOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}navOpenKeys`)) || [],
  },
  subscriptions: {

    setup ({ dispatch }) {
      dispatch({ type: 'query' })
      let tid
      /**
      window.onresize = () => {
        clearTimeout(tid)
        tid = setTimeout(() => {
          dispatch({ type: 'changeNavbar' })
        }, 300)
      } */
    },

  },
  effects: {

    * query ({ payload,}, { call, put }) {
      const { success, user } = yield call(query, payload)
      if (success && user) {
        let menuList,permissions
        const data = yield call(menuService.queryNav);
        menuList=data.menuList
        permissions=data.permissions
        sessionStorage.setItem('menuList',JSON.stringify(menuList))
        sessionStorage.setItem('permissions',JSON.stringify(permissions))
        let defaultPage=menuList[0].url
        if(!defaultPage){
          const defaultPageId=menuList[0].menuId
          menuList.map((item)=>{
            if(item.parentId==defaultPageId){
              defaultPage=item.url
              return
            }
          })
        }
    
        if(!defaultPage){
          defaultPage=""
        }
        sessionStorage.setItem('defaultPage',defaultPage)
        sessionStorage.setItem('userId',user.userId)
        
        yield put({
          type: 'setOrgList',
          orgList: data.orgList
        }) 
        yield put({
          type: 'setCurrentOrgReducer',
          org: data.currentOrg
        })
        /**
        let menuListString=sessionStorage.getItem('menuList')
        let permissionsString=sessionStorage.getItem('permissions')
        if(!menuListString||!permissionsString){
          const data = yield call(menuService.queryNav)
          menuList=data.menuList
          permissions=data.permissions
          sessionStorage.setItem('menuList',JSON.stringify(menuList))
          sessionStorage.setItem('permissions',JSON.stringify(permissions))
        }else{
          menuList=JSON.parse(menuListString)
          permissions=JSON.parse(permissionsString)
        }**/
        const list = menuList
        let menu = list
        permissions.visit = list.map(item => item.id)
        
        yield put({
          type: 'updateState',
          payload: {
            user,
            permissions,
            menu,
          },
        })
        if (location.pathname === '/login') {
          yield put(routerRedux.push(defaultPage))
          // yield put(routerRedux.push('/dashboard'))
        }
        
      } else if (config.openPages && config.openPages.indexOf(location.pathname) < 0) {
        let from = location.pathname
        window.location = `${location.origin}/login?from=${from}`
      }
    },

    * logout ({payload,}, { call, put }) {
      const data = yield call(logout, parse(payload))
      if (data.success) {
        sessionStorage.removeItem("userId");
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("yct_userinfo");
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },
    * changePassWord({ payload }, { call, put }) {
      const data = yield call(changePassWordService, { password: payload.password, newPassword: payload.newPassword })
      if (data.success) {
        sessionStorage.removeItem("userId");
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("yct_userinfo");
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },
    * changeNavbar (action, { put, select }) {
      const { app } = yield (select(_ => _))
      const isNavbar = document.body.clientWidth < 769
      if (isNavbar !== app.isNavbar) {
        yield put({ type: 'handleNavbar', payload: isNavbar })
      }
    },
    * setCurrentOrg({org},{call, put}) {
      const res = yield call(refreshTokenByOrg, { orgId: org.id });
      if(res.code === 0) {
        sessionStorage.setItem('token',res.data.token)
      }
      const data = yield call(menuService.queryNav);
      yield put({
        type: 'query'
      })
      return yield put({
        type: 'setCurrentOrgReducer',
        org: org,
        url: data.menuList[0].url
      })
    }
  },
  reducers: {
    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
    setCurrentOrgReducer(state, action) {
      return {...state, currentOrg: action.org}
    },
    setOrgList(state, action) {
      return {...state, orgList: action.orgList};
    },
    switchSider (state) {
      window.localStorage.setItem(`${prefix}siderFold`, !state.siderFold)
      return {
        ...state,
        siderFold: !state.siderFold,
      }
    },

    switchTheme (state) {
      window.localStorage.setItem(`${prefix}darkTheme`, !state.darkTheme)
      return {
        ...state,
        darkTheme: !state.darkTheme,
      }
    },

    switchMenuPopver (state) {
      return {
        ...state,
        menuPopoverVisible: !state.menuPopoverVisible,
      }
    },

    handleNavbar (state, { payload }) {
      return {
        ...state,
        isNavbar: payload,
      }
    },

    handleNavOpenKeys (state, { payload: navOpenKeys }) {
      return {
        ...state,
        ...navOpenKeys,
      }
    },
  },
}
